<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class m_client extends CI_Model{
	
	function __construct()
	{
		parent::__construct();
	} 
	
/*
|--------------------------------------------------------------------------
| 验证账号
|--------------------------------------------------------------------------
*/	

	//获取企业信息
	function chklogin($username,$password,$client_key,$device_id)
	{
		//验证device_id
		$chk_device_id = $this->db->query('select `client_key` from  `'.$this->db->dbprefix('api_oauth_client_key').'` where `client_key`=\''.$client_key.'\' ')->row_array();
		if(empty($chk_device_id)){
			return '-10002';	#device_id不存在，非法
		}
		
		//验证账号
		$chk_account =  $this->db->query('select `id`,`user_pwd`,`user_salt`,`status` from  `'.$this->db->dbprefix('u_account').'` where `username`=\''.$username.'\' ')->row_array();
		if(empty($chk_account)){
			return '-20002';	#账号不存在
		}else{
			if(empty($chk_account['status'])){
				return '-20003';	#账号已冻结	
			}else{
				$this->load->library('PwdEncryption');
				$p = new PwdEncryption();
				if($p->getEncryptPwd($password,$chk_account['user_salt'])==$chk_account['user_pwd']){
					
					return $chk_account['id'];		#帐密正确
				}else{
					return '-20001';#帐密不正确
				}
			}
		}
	}

	
	//update api_device_sync的token
	function update_api_token($user_id,$device_id,$client_key,$token)
	{
		$this->db->query('delete from `'.$this->db->dbprefix('api_device_sync').'` where `user_id`=\''.$user_id.'\' and `device_id`=\''.$device_id.'\'  ');
		return $this->db->query('insert into `'.$this->db->dbprefix('api_device_sync').'` set 
				`user_id`=\''.$user_id.'\',
				`device_id`=\''.$device_id.'\',
				`client_key`=\''.$client_key.'\',
				`token`=\''.$token.'\',
				`device_time`=\''.time().'\'
		');
	}
	
	
/*
|--------------------------------------------------------------------------
| 注册，返回token
{host}/index.php/api/client/reg
|--------------------------------------------------------------------------
*/	
	function reg($username,$password,$client_key,$device_id,$key)
	{
		//验证device_id
		$chk_device_id = $this->db->query('select `id` from  `'.$this->db->dbprefix('api_oauth_client_key').'` where `client_key`=\''.$client_key.'\' ')->row_array();
		if(empty($chk_device_id)){
			return '-10002';	#device_id不存在，非法
		}
		
		//验证账号
		$chk_account =  $this->db->query('select `id` from  `'.$this->db->dbprefix('u_account').'` where `username`=\''.$username.'\' ')->row_array();
		if(!empty($chk_account)){
			return '-20004';	#账号已存在
		}else{
			$len = strlen($username);
			if($len > 50 or $len < 6){
				return '-20006';	#账号长度不正确
			}
			//if(!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$username)){
				//return '-20007';	#账号必须为邮件
			//}
			$sqlext = '';
			//如果有密钥
			if(!empty($key)){				
				$chkkey = $this->chekey($key);
				if(is_array($chkkey)){
					$sqlext.=' `member_who`=\''.$chkkey['type'].'\',
					`company_account`=\''.$chkkey['account'].'\',
					`keytime`=\''.$chkkey['utime'].'\',
					   ';	
					$this->usekey($key);
					$key_status = '1';
				}else{
					$key_status = $chkkey;	
				}
			}else{
				
				$key_status = '0';	
			}
			
			
			//生成密码
			$this->load->library('PwdEncryption');	
			$p = new PwdEncryption();
			$psw = $p->genEncryptPwd(trim($this->input->post('password')));
			//account表
			$floder = creat_folder_name();
			$floder_pre = date('y').date('m');
			$this->db->query('insert into  `'.$this->db->dbprefix('u_account').'`  set
				`username`=\''.$username.'\' ,
				`user_pwd`=\''.$psw[0].'\',
				`user_salt`=\''.$psw[1].'\',
				`appfrom`=\''.$chk_device_id['id'].'\',
				`floder`=\''.$floder.'\',
				`floder_pre`=\''.$floder_pre.'\',
				`status`=\'1\'
			 ');	
		 	$cid = $this->db->insert_id();
			//创建文件夹
			$path = './pic/'.$floder_pre.'/'.$floder;
			creatfolder($path);
			
			//上传头像（如果有）
			if($_FILES['userfile']['size']>0){
				$this->load->library('upload');
				$config['upload_path'] = './pic/'.$floder_pre.'/'.$floder.'/company';
				$config['allowed_types'] = '*';
				$config['max_size'] = '50000';
				$config['max_width']  = '6400';
				$config['max_height']  = '6400';
				$config['encrypt_name']  = TRUE;
				
				if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'],0755,true)	;
				}
				
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				if (!$this->upload->do_upload())
				{
					$error = array('error' => $this->upload->display_errors());
					//print_r($error);
					$head_pic = '-60001';
				} else{
					$data = array('upload_data' => $this->upload->data());
					$pic_name = $data['upload_data']['file_name'];
					//print_r($this->upload->data());
					$head_pic = '1';
				}
				
				$sqlext.= ' `member_head`=\''.$pic_name.'\',  ';
			}else{
				$sqlext.= '   ';	
				$head_pic = '0';
			}
			
			$this->db->query('insert into  `'.$this->db->dbprefix('u_banseinfo').'`  set
				`account_id`=\''.$cid.'\' ,
				`u_name`=\''.$username.'\',
				`regtime`=\''.time().'\',
				`usetime`=\''.strtotime(USETIME).'\',
				'.$sqlext.'
				`verifytime`=\''.time().'\'
			 ');
			
			
			$this->import_pro_from_no4e($cid,$chkkey['account']);
			
			return 	array('cid'=>$cid,'key_status'=>$key_status,'head_pic_static'=>$head_pic);
		}
		
 
	}	
	


/*
|--------------------------------------------------------------------------
|  验证密钥
{host}/index.php/api/client/chekey
|--------------------------------------------------------------------------
*/
	function chekey($key,$account='')
	{
		$res = $this->db->query('select * from  `'.$this->db->dbprefix('u_login_key').'` where `key`=\''.$key.'\' limit 1 ')->row_array();
		if(empty($res)){
			return '-50001';	
		}
			
		if($res['used']=='1'){
			return '-50002';	
		}
		
		if($res['account']!=$account && !empty($account)){
			return '-50003';		
		}
			 
		return array('type'=>$res['type'],'account'=>$res['account'],'utime'=>$res['utime']);
	}

	function usekey($key)
	{
		return $this->db->query('update  `'.$this->db->dbprefix('u_login_key').'` set used=1,usetime=\''.time().'\'  where `key`=\''.$key.'\' limit 1 ');	
	}

/*
|--------------------------------------------------------------------------
| 根据token与ID返回好友列表
{host}/index.php/api/client/good_freind_ids
|--------------------------------------------------------------------------
*/	
	function good_freind_ids($member_id)
	{
		return $this->db->query('select toid  from `'.$this->db->dbprefix('u_friend').'`   where fromid = \''.$member_id.'\' ')->result_array();	
	}
	
	
	
	
/*
|--------------------------------------------------------------------------
| 根据token与ID 添加好友与解除好友接口
{host}/index.php/api/client/update_friend
|--------------------------------------------------------------------------
*/	
	function update_friend($member_id,$friend_id,$operate)
	{
		$chk = $this->db->query('select toid  from `'.$this->db->dbprefix('u_friend').'`   where  fromid = \''.$member_id.'\' and toid = \''.$friend_id.'\'  ')->row_array();
		if(!empty($chk['toid'])){
			if($operate == '1'){
				return '-30001';	
			}else{
				$this->db->query('delete from `'.$this->db->dbprefix('u_friend').'`  where  fromid = \''.$member_id.'\' and toid = \''.$friend_id.'\' limit 1 ');	
				$this->db->query('delete from `'.$this->db->dbprefix('u_friend').'`  where  fromid = \''.$friend_id.'\' and toid = \''.$member_id.'\' limit 1 ');
				return '1';	
			}
		}else{
			if($operate == '1'){
				$this->db->query('insert into `'.$this->db->dbprefix('u_friend').'` set  fromid = \''.$member_id.'\' , toid = \''.$friend_id.'\'   ');	
				$this->db->query('insert into `'.$this->db->dbprefix('u_friend').'` set  fromid = \''.$friend_id.'\' , toid = \''.$member_id.'\'   ');
				return '1';		
			}else{
				return '-30002';		
			}
		}
	}
	

	
	
/*
|--------------------------------------------------------------------------
| 产品收藏
{host}/index.php/api/client/product_collect
|--------------------------------------------------------------------------
*/	
	function product_collect($member_id,$product_id,$operate)
	{
		$chk = $this->db->query('select member_id  from `'.$this->db->dbprefix('u_product_collect').'`   where  member_id = \''.$member_id.'\' and product_id = \''.$product_id.'\'  ')->row_array();
		if(!empty($chk['member_id'])){
			if($operate == '1'){
				return '-30001';	
			}else{
				$this->db->query('delete from `'.$this->db->dbprefix('u_product_collect').'`  where  member_id = \''.$member_id.'\' and product_id = \''.$product_id.'\' limit 1 ');	
				
				return '1';	
			}
		}else{
			if($operate == '1'){
				$this->db->query('insert into `'.$this->db->dbprefix('u_product_collect').'` set  member_id = \''.$member_id.'\' , product_id = \''.$product_id.'\'   ');	
				
				return '1';		
			}else{
				return '-30002';		
			}
		}
	}
	
	//更新产品收藏数量
	function update_pro_collect_info($product_id,$operate)
	{
		$num = ($operate=='1')?'+1':'-1';
		$this->db->query('update `'.$this->db->dbprefix('u_pro').'` set  `product_collect_count` = `product_collect_count` '.$num.' where id = \''.$product_id.'\'   ');		
	}
	



/*
|--------------------------------------------------------------------------
| 根据token 获取会员收藏产品列表接口
{host}/index.php/api/client/get_collect_products
|--------------------------------------------------------------------------
*/	
	function get_collect_products($member_id,$page,$count_per_page,$search)
	{
		if(!empty($search)){
			$where = ' and `proname` like \'%'.$search.'%\' ';	
		}
		$page = $page*$count_per_page;
		$proinfo = $this->db->query('select `id`,`account_id`,`proname`,`prodes`,`product_collect_count` from `'.$this->db->dbprefix('u_pro').'`  where 1  and `id` in ( select `product_id` from `'.$this->db->dbprefix('u_product_collect').'` where `member_id`=\''.$member_id.'\' )  '.$where.'  order by id desc limit '.$page.','.$count_per_page.' ')->result_array();
		if(!empty($proinfo)){
			foreach($proinfo as $key=>$line){
				$member_info = $this->get_member_info($line['account_id']);
				
				$pic = $this->db->query(' select `img`,`type` from `'.$this->db->dbprefix('u_pro_img').'` where `pid`=\''.$line['id'].'\'  ')->result_array();	
				if(!empty($pic)){
					foreach($pic as $picline){
						if($picline['type']=='0'){
							$pic_array[] = base_url().'pic/'.$member_info['floder_pre'].'/'.$member_info['floder'].'/pro/s/'.$picline['img'];		
						}else{
							$pic_array[] = 	$picline['img'];
						}					
					}
				}else{
					$pic_array = array();	
				}
				
				$proinfo[$key]['product_pics'] = $pic_array;
				$proinfo[$key]['memberinfo'] = $member_info;
				unset($pic_array);
			}
		}else{
			return array();	
		}
		return $proinfo;
	}
	


/*
|--------------------------------------------------------------------------
| 根据token 评论产品
{host}/index.php/api/client/comment_product
|--------------------------------------------------------------------------
*/	
	function comment_product($member_id,$product_id,$comment)
	{
		return $this->db->query('insert into `'.$this->db->dbprefix('u_product_comment').'` set 
		`member_id`=\''.$member_id.'\',
		`product_id`=\''.$product_id.'\',
		`ctime`=\''.time().'\',
		`comment`=\''.$comment.'\' ');
	}


/*
|--------------------------------------------------------------------------
| 根据token 产品评论
{host}/index.php/api/client/get_product_comments
|--------------------------------------------------------------------------
*/	
	function get_product_comments($product_id,$page,$count_per_page)
	{
		$page = $page*$count_per_page;
		return $this->db->query('select a.*,b.member_head from  `'.$this->db->dbprefix('u_product_comment').'` a left join `'.$this->db->dbprefix('u_banseinfo').'`  b  on a.member_id=b.account_id where a.product_id=\''.$product_id.'\' order by a.ctime desc limit '.$page.','.$count_per_page.' ')->result_array();
	}

	
	function get_member_info($member_id)
	{
		return $this->db->query('select a.username,a.`floder`,a.`floder_pre`,b.`member_head`,b.`u_name`,b.`company_name`,b.`member_head`  from  `'.$this->db->dbprefix('u_account').'` a left join  `'.$this->db->dbprefix('u_banseinfo').'` b on a.id=b.account_id where a.`id`=\''.$member_id.'\' limit 1 ')->row_array();	
	}
	
	
	
	
/*
|--------------------------------------------------------------------------
| 根据token 产品详情
{host}/index.php/api/client/get_product
|--------------------------------------------------------------------------
*/	
	function get_product($product_id)
	{
		return $this->db->query('select `proname`,`prodes` from  `'.$this->db->dbprefix('u_pro').'`   where  id=\''.$product_id.'\'   limit 1 ')->row_array();
	}	
	
	function get_product_img($product_id)
	{
		$temp = $this->db->query('select a.`img`,a.`type`,b.floder_pre,b.floder from  `'.$this->db->dbprefix('u_pro_img').'` a left join  `'.$this->db->dbprefix('u_account').'` b on a.account_id=b.id  where  a.pid=\''.$product_id.'\'    ')->result_array();
		if(!empty($temp)){
			foreach($temp as $picline){
				if($picline['type']=='0'){
					$pic_array[] = base_url().'pic/'.$picline['floder_pre'].'/'.$picline['floder'].'/pro/b/'.$picline['img'];		
				}else{
					$pic_array[] = 	$picline['img'];
				}					
			}
			return $pic_array;
		}else{
			return array();	
		}
	}		
	

/*
|--------------------------------------------------------------------------
| 根据token 商人产品接口
{host}/index.php/api/client/merchant_product_list
|--------------------------------------------------------------------------
*/	
	function merchant_product_list($member_id,$page,$count_per_page,$product_type_id)
	{
		if(!empty($product_type_id)){
			$where = ' and `proclass`=\''.$product_type_id.'\' ';	
		}
		$page = $page*$count_per_page;
		$proinfo = $this->db->query('select `id`,`proname`,`prodes`,`product_collect_count` from  `'.$this->db->dbprefix('u_pro').'`   where  account_id=\''.$member_id.'\' '.$where.'  order by id desc  limit '.$page.','.$count_per_page.' ')->result_array();
		if(!empty($proinfo)){
			$member_info = $this->get_member_info($member_id);
			foreach($proinfo as $key=>$line){			
				$pic = $this->db->query(' select `img`,`type` from `'.$this->db->dbprefix('u_pro_img').'` where `pid`=\''.$line['id'].'\'  ')->result_array();	
				if(!empty($pic)){
					foreach($pic as $picline){
						if($picline['type']=='0'){
							$pic_array[] = base_url().'pic/'.$member_info['floder_pre'].'/'.$member_info['floder'].'/pro/s/'.$picline['img'];	
							
						}else{
							$pic_array[] = 	$picline['img'];						
						}					
					}
				}else{
					$pic_array = array();	
				}
			
				$proinfo[$key]['product_introduce'] = $proinfo[$key]['prodes'];
				$proinfo[$key]['product_pics'] = $pic_array;
				
				if(!empty($pic_array[0])){
					$temp = @getimagesize($pic_array[0]);
					if(!empty($temp)){
						$proinfo[$key]['first_pic_width'] = $temp[0];
						$proinfo[$key]['first_pic_height'] = $temp[1];	
					}else{
						$proinfo[$key]['first_pic_width'] = 0;
						$proinfo[$key]['first_pic_height'] = 0;		
					}
				}else{
					$proinfo[$key]['first_pic_width'] = 0;
					$proinfo[$key]['first_pic_height'] = 0;			
				}
				
				//$proinfo[$key]['username'] = $member_info['username'];
				unset($pic_array);
			}
		}
		return $proinfo;
	}	

/*
|--------------------------------------------------------------------------
| 根据token 获取商人联系方式
{host}/index.php/api/client/get_merchant_contact
|--------------------------------------------------------------------------
*/	
	function get_merchant_contact($member_id)
	{
		return $this->db->query('select `type`,`content`  from  `'.$this->db->dbprefix('u_contact').'`   where  account_id=\''.$member_id.'\'  and lan=\'1\' and `type` in  (2,3,4,5)  ')->result_array();
	}	




/*
|--------------------------------------------------------------------------
| 根据token 基本信息
{host}/index.php/api/client/get_my_baseinfo
|--------------------------------------------------------------------------
*/	
	function get_my_baseinfo($member_id)
	{
		return $this->db->query('select a.`member_head` ,a.`u_name`,a.`member_position`,a.`company_name` ,b.floder,b.floder_pre from  `'.$this->db->dbprefix('u_banseinfo').'` a left join  `'.$this->db->dbprefix('u_account').'` b  on a.account_id=b.id   where  account_id=\''.$member_id.'\'  limit 1  ')->row_array();
	}	










/*
|--------------------------------------------------------------------------
| 根据token 添加新产品
{host}/index.php/api/client/add_new_product
|--------------------------------------------------------------------------
*/
	function add_new_product($member_id,$product_id,$product_name,$product_detail,$tags)
	{
		$product_id = intval($product_id);
		if(empty($product_id)){
			$this->db->query('insert into `'.$this->db->dbprefix('u_pro').'` set
			`account_id`=\''.$member_id.'\',
			`proname`=\''.$product_name.'\',
			`create_time`=\''.time().'\',
			`prodes`=\''.$product_detail.'\' ');
			$pid = $this->db->insert_id();
			//标签
			$tag = json_decode($tags);
			if(is_array($tag) && !empty($tag[0])){
				foreach($tag as $line){
					if(!empty($line)){
						$sql.=' (\''.$member_id.'\',\''.$pid.'\',\''.trim($line).'\'),';	
					}
				}
				$this->db->query('insert into `'.$this->db->dbprefix('u_pro_tag').'` (account_id,pro_id,pro_tag) values
				 '.substr($sql,0,-1));
			}
			return $pid;
		}else{
			$this->db->query('update `'.$this->db->dbprefix('u_pro').'` set
			`proname`=\''.$product_name.'\',
			`modifie_time`=\''.time().'\',
			`prodes`=\''.$product_detail.'\' 
			where `id`=\''.$product_id.'\' and `account_id`=\''.$member_id.'\' ');
			
			//标签
			$tag = json_decode($tags);
			if(is_array($tag)){
				$this->db->query('delete from `'.$this->db->dbprefix('u_pro_tag').'` where account_id=\''.$member_id.'\' and pro_id=\''.$product_id.'\' ');
				foreach($tag as $line){
					if(!empty($line)){
						$sql.=' (\''.$member_id.'\',\''.$product_id.'\',\''.trim($line).'\'),';	
					}
				}
				$this->db->query('insert into `'.$this->db->dbprefix('u_pro_tag').'` (account_id,pro_id,pro_tag) values
				 '.substr($sql,0,-1));
			}
			return $product_id;
		}
		
	}
	
	
/*
|--------------------------------------------------------------------------
|  6、上传产品图片
{host}/index.php/api/client/upload_product_pic
|--------------------------------------------------------------------------
*/
	function upload_product_pic($member_id,$product_id)
	{
		$query = $this->db->query('select `floder_pre`,`floder` 
			from `'.$this->db->dbprefix('u_account').'` 
			where `id` = \''.intval($member_id).'\'')->row_array();
		if(!isset($query['floder_pre'])){
			return '-1';
		}

		if($_FILES['userfile']['size']>0){
			$this->load->library('upload');
			$config['upload_path'] = 'pic/'.$query['floder_pre'].'/'.$query['floder'].'/pro/b/';
			$config['allowed_types'] = '*';
			$config['max_size'] = '50000';
			$config['max_width']  = '4000';
			$config['max_height']  = '3000';
			$config['encrypt_name']  = TRUE;
		
				if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'],0755,true)	;
				}
				
			$this->load->library('upload', $config);
			$this->upload->initialize($config);
			if (!$this->upload->do_upload())
			{
				$error = array('error' => $this->upload->display_errors());
				return '-60001';
			} else{
				$data = array('upload_data' => $this->upload->data());
				$pic_name = $data['upload_data']['file_name'];
				$old_image = APPPATH.'../pic/'.$query['floder_pre'].'/'.$query['floder'].'/pro/b/'.$pic_name;
				$m_image = APPPATH.'../pic/'.$query['floder_pre'].'/'.$query['floder'].'/pro/m/'.$pic_name;
				$s_image = APPPATH.'../pic/'.$query['floder_pre'].'/'.$query['floder'].'/pro/s/'.$pic_name;
				imagezoom( $old_image, $m_image,  $this->config->item('pro_pic_w'),$this->config->item('pro_pic_w') );
				imagezoom( $old_image, $s_image,  $this->config->item('pro_pic_thumb_w'),$this->config->item('pro_pic_thumb_w') );
				
				return $this->db->query('insert into `'.$this->db->dbprefix('u_pro_img').'` set
				`img`=\''.$pic_name.'\'
				, `pid`=\''.$product_id.'\' , `account_id`=\''.$member_id.'\' ');
					 
			}
			
			
		}else{
			return 	'-60002';
		}
		//return $this->db->insert_id();
	}



/*
|--------------------------------------------------------------------------
| 根据token 商人列表
{host}/index.php/api/client/member_list
|--------------------------------------------------------------------------
*/	
	function member_list($who='',$page,$count_per_page,$friend_only='',$account_id='')
	{
		if(!empty($who)){
			$where.= ' and `member_who`=\''.$who.'\' ';	
		}
		if($friend_only=='1'){
			$where.= ' and a.`account_id` in (select toid from   `'.$this->db->dbprefix('u_friend').'` where fromid='.$account_id.'   ) ';	
		}		
		
		$page = $page*$count_per_page;
		$temp = $this->db->query('select a.`account_id`,a.`member_head`,a.`member_position`,a.`u_name`,a.`member_who`,a.`company_name`,a.`procount`,a.`regtime` as update_time,b.floder_pre,b.floder from `'.$this->db->dbprefix('u_banseinfo').'` a left join `'.$this->db->dbprefix('u_account').'` b on a.account_id=b.id where 1 '.$where.' order by `account_id` desc limit '.$page.','.$count_per_page.' ')->result_array(); 
		foreach($temp as $key=>$line){
			//消息
			//$last_message = $this->db->query(' select `message`,`mtime` from `'.$this->db->dbprefix('u_message').'` where `member_id`=\''.$line['account_id'].'\' order by id desc limit 1   ')->row_array();	
			//$temp[$key]['update_time'] = $last_message['mtime'];
			//$temp[$key]['message'] = $last_message['message'];
			 
			//产品
			$pic = $this->db->query(' select `img`,`type` from `'.$this->db->dbprefix('u_pro_img').'` where `account_id`=\''.$line['account_id'].'\' order by id desc limit 4   ')->result_array();	
			if(!empty($pic)){
				foreach($pic as $picline){
					if($picline['type']=='0'){
						$pic_array[] = base_url().'pic/'.$line['floder_pre'].'/'.$line['floder'].'/pro/s/'.$picline['img'];		
					}else{
						$pic_array[] = 	$picline['img'];
					}					
				}
			}else{
				$pic_array = array();	
			}
			$temp[$key]['products'] = $pic_array;
			unset($pic_array);
			if(!empty($temp[$key]['member_head'])){
				$temp[$key]['member_head'] = base_url().'pic/'.$temp[$key]['floder_pre'].'/'.$temp[$key]['floder'].'/company/'.trim($temp[$key]['member_head']);
			}
			
		}
		return $temp;
	}
	
	function member_list_num($who='',$friend_only='',$account_id='')
	{
		if(!empty($who)){
			$where.= ' and `member_who`=\''.$who.'\' ';	
		}
		if($friend_only=='1'){
			$where.= ' and  `account_id` in (select toid from   `'.$this->db->dbprefix('u_friend').'` where fromid='.$account_id.'   ) ';	
		}
		$res = $this->db->query('select count(*) as num from `'.$this->db->dbprefix('u_banseinfo').'`  where 1 '.$where.'    ')->row_array(); 
		
		return $res ['num'];
	}	
	


/*
|--------------------------------------------------------------------------
| 根据token 产品导航列表接口
{host}/index.php/api/client/product_list
|--------------------------------------------------------------------------
*/	
	function product_list($product_type_id,$page,$count_per_page,$tag='')
	{
		if(!empty($tag)){
			$where = ' and a.id in (select pro_id from `'.$this->db->dbprefix('u_pro_tag').'` where  `pro_tag`=\''.$tag.'\') ';	
		}
		$page = $page*$count_per_page;
		$temp = $this->db->query('select a.`id`,a.`proname`,a.`prodes`,a.`product_collect_count`,a.`account_id`,b.`member_head`,b.`u_name`,b.`company_name`,c.floder_pre,c.floder from 
			`'.$this->db->dbprefix('u_pro').'` a left join `'.$this->db->dbprefix('u_banseinfo').'` b on a.account_id=b.account_id   
			left join `'.$this->db->dbprefix('u_account').'` c on a.account_id=c.id			
			 where 1 '.$where.' order by a.`id` desc limit '.$page.','.$count_per_page.' ')->result_array(); 	
		
		foreach($temp as $key=>$line){
			//产品
			$pic = $this->db->query(' select `img`,`type` from `'.$this->db->dbprefix('u_pro_img').'` where `pid`=\''.$line['id'].'\' order by id desc limit 4   ')->result_array();	
			if(!empty($pic)){
				foreach($pic as $picline){
					if($picline['type']=='0'){
						$pic_array[] = base_url().'pic/'.$line['floder_pre'].'/'.$line['floder'].'/pro/s/'.$picline['img'];		
					}else{
						$pic_array[] = 	$picline['img'];
					}					
				}
			}else{
				$pic_array = array();	
			}
			$temp[$key]['product_pics'] = $pic_array;
					
				if(!empty($pic_array[0])){
					$pictemp = @getimagesize($pic_array[0]);
					if(!empty($pictemp)){
						$temp[$key]['first_pic_width'] = $pictemp[0];
						$temp[$key]['first_pic_height'] = $pictemp[1];	
					}else{
						$temp[$key]['first_pic_width'] = 0;
						$temp[$key]['first_pic_height'] = 0;		
					}
				}else{
					$temp[$key]['first_pic_width'] = 0;
					$temp[$key]['first_pic_height'] = 0;			
				}
				
			unset($pic_array);
			
		}
		return $temp;
	}

	//返回某会员所有收藏产品ID
	function product_collect_list($member_id)
	{
		return $this->db->query('select `product_id` from `'.$this->db->dbprefix('u_product_collect').'` where `member_id`=\''.$member_id.'\' ')->result_array();
	}


/*
|--------------------------------------------------------------------------
|  添加消息
{host}/index.php/api/client/add_message
|--------------------------------------------------------------------------
*/
	function add_message($member_id,$from_member_id,$type,$message,$title='',$message_type='')
	{
		$this->db->query('insert into `'.$this->db->dbprefix('u_message').'`
			set `member_id`=\''.$member_id.'\',
			`from_member_id`=\''.$from_member_id.'\',
			`type`=\''.$type.'\',
			`message`=\''.addslashes($message).'\',
			`title`=\''.$title.'\',
			`message_type`=\''.$message_type.'\',
			`mtime`=\''.time().'\'
			 ');
		return $this->db->insert_id();	
	}


//根据用户ID获取用户名
	function get_account_name($member_id)
	{
		return $this->db->query('select `u_name` from `'.$this->db->dbprefix('u_banseinfo').'` where `account_id`=\''.$member_id.'\' limit 1 ')->row_array();	
	}


//根据产品ID获取用户名
	function get_account_name_frompro($proid)
	{
		return $this->db->query('select `account_id`,`u_name` from `'.$this->db->dbprefix('u_banseinfo').'` where `account_id`=(select `account_id` from `'.$this->db->dbprefix('u_pro').'` where id= \''.$proid.'\'   )   limit 1 ')->row_array();	
	}





/*
|--------------------------------------------------------------------------
|  获取消息
{host}/index.php/api/client/get_message_list
|--------------------------------------------------------------------------
*/
	function get_message_list($member_id,$page,$count_per_page)
	{
		$info = $this->db->query('select a.*,b.u_name as member_name,c.u_name as from_member_name from  `'.$this->db->dbprefix('u_message').'` a 
		left join   `'.$this->db->dbprefix('u_banseinfo').'` b on a.member_id=b.account_id  
		left join   `'.$this->db->dbprefix('u_banseinfo').'` c on a.from_member_id=c.account_id  
		where  member_id=\''.$member_id.'\' or from_member_id=\''.$member_id.'\'    order by mtime desc  limit '.$page.','.$count_per_page.' ')->result_array();
		
		return $info;
	}





/*
|--------------------------------------------------------------------------
| 根据token与企业账号新增修改企业标签
{host}/index.php/api/client/account_tag
|--------------------------------------------------------------------------
*/	
	function account_tag($member_id,$tags)
	{	
		$tag = json_decode($tags,true);
		if(!is_array($tag)){
			return '-20008';	
		}else{
			if(!empty($tag)){
				$this->db->query('delete from `'.$this->db->dbprefix('u_tag').'`  where account_id=\''.$member_id.'\'  ');	
				foreach($tag as $line){
					if(!empty($line)){
						$sql.=' (\''.$member_id.'\',\''.trim($line).'\'),';	
					}
				}
				$res = $this->db->query('insert into `'.$this->db->dbprefix('u_tag').'` (account_id,tag) values
				 '.substr($sql,0,-1));
				if($res){
					return '1';	
				}
			}
		}
	}

/*
|--------------------------------------------------------------------------
| 根据token与企业账号获取企业标签
{host}/index.php/api/client/get_account_tag
|--------------------------------------------------------------------------
*/	
	function get_account_tag($member_id)
	{	
		
		return	$this->db->query('select `tag` from `'.$this->db->dbprefix('u_tag').'`  where account_id=\''.$member_id.'\'  ')->result_array();	
			
	}




	
/*
|--------------------------------------------------------------------------
| 根据token与企业账号返回企业信息
{host}/index.php/api/client/get_company_info
|--------------------------------------------------------------------------
*/		
	
	function get_company_info($companyuser)
	{
		return $this->db->query('select a.company_user,a.user_email,a.logo,a.bgpic,b.company_id,b.company_name from `'.$this->db->dbprefix('company_account').'` a ,`'.$this->db->dbprefix('company_baseinfo').'` b where a.id=b.company_id and a.company_user = \''.$companyuser.'\' ')->row_array();
	}	
	
	function get_company_contact($company_id,$lan='1')
	{
		return $this->db->query('select type ,title ,	content from `'.$this->db->dbprefix('company_contact').'`  where company_id=\''.$company_id.'\' and lan=\''.$lan.'\'  ')->result_array();
	}	




/*
|--------------------------------------------------------------------------
| 根据token与企业账号返回企业产品所有信息
{host}/index.php/api/client/get_company_pro_list
|--------------------------------------------------------------------------
*/	
	function get_company_pro_list($companyuser,$lan='1')
	{
		if(is_array($companyuser)){
			foreach($companyuser as $cline){
				$where.= ' or  company_user = \''.$companyuser.'\' '	;
			}
			$where = substr($where,2);
		}else{
			$where = '   company_user = \''.$companyuser.'\' '	;
		}	
		$pro_list =  $this->db->query('select `id`,`proname`,`prodes`,`company_id` from `'.$this->db->dbprefix('company_pro').'`  where company_id in( select id  from `'.$this->db->dbprefix('company_account').'`   where  1 and ('.$where.') )  and lan=\''.$lan.'\' and status=1 ')->result_array();
		
		if(!empty($pro_list)){
			foreach($pro_list as $key => $pline){
				$pro_list[$key]['proimg'][] = $this->db->query('select `img` from `'.$this->db->dbprefix('company_pro_img').'` where pid=\''.$pro_list[$key]['id'].'\' ');
			}	
			if(!empty($pro_list[$key]['proimg'])){
				foreach($pro_list[$key]['proimg'] as $pickey=>$temppic){
					$pro_list[$key]['proimg'][$pickey]	= base_url().'pic/'.$company_user.'/pro/s/'.$temppic;
				}
			}
		}
		
		return $pro_list;
	}	





/*
|--------------------------------------------------------------------------
| 更新联系方式
{host}/index.php/api/client/update_contact
|--------------------------------------------------------------------------
*/
	function update_contact($account_id,$u_name='',$member_position='',$company_name='',$tel='',$phone='',$email='',$address='')
	{
		if(!empty($u_name) || !empty($member_position) || !empty($company_name)){
			$this->db->query('update `'.$this->db->dbprefix('u_banseinfo').'` set `u_name`=\''.$u_name.'\',`member_position`=\''.$member_position.'\',`company_name`=\''.$company_name.'\' where  `account_id`=\''.$account_id.'\'  limit 1 ');	
		}
		if(!empty($tel)){
			$this->db->query('delete from `'.$this->db->dbprefix('u_contact').'` where  `account_id`=\''.$account_id.'\' and  `lan`=\'1\' and `type`=\'5\' limit 1 ');
			$this->db->query('insert into `'.$this->db->dbprefix('u_contact').'` set `title`=\'座机\',`content`=\''.$tel.'\' ,  `account_id`=\''.$account_id.'\' ,  `lan`=\'1\' , `type`=\'5\'   ');	
		}
		if(!empty($phone)){
			$this->db->query('delete from `'.$this->db->dbprefix('u_contact').'` where  `account_id`=\''.$account_id.'\' and  `lan`=\'1\' and `type`=\'4\' limit 1 ');
			$this->db->query('insert into `'.$this->db->dbprefix('u_contact').'` set `title`=\'手机\',`content`=\''.$phone.'\' ,  `account_id`=\''.$account_id.'\' ,  `lan`=\'1\' , `type`=\'4\'  ');	
		}
		if(!empty($email)){
			$this->db->query('delete from `'.$this->db->dbprefix('u_contact').'` where  `account_id`=\''.$account_id.'\' and  `lan`=\'1\' and `type`=\'2\' limit 1 ');
			$this->db->query('insert into `'.$this->db->dbprefix('u_contact').'` set `title`=\'邮箱\',`content`=\''.$email.'\' ,  `account_id`=\''.$account_id.'\' ,  `lan`=\'1\' , `type`=\'2\'  ');	
		}
		if(!empty($address)){
			$this->db->query('delete from `'.$this->db->dbprefix('u_contact').'` where  `account_id`=\''.$account_id.'\' and  `lan`=\'1\' and `type`=\'3\' limit 1 ');
			$this->db->query('insert into `'.$this->db->dbprefix('u_contact').'` set `title`=\'地址\',`content`=\''.$address.'\' ,  `account_id`=\''.$account_id.'\' ,  `lan`=\'1\' , `type`=\'3\'  ');	
		}		
		return '1';
	}


	
/*
|--------------------------------------------------------------------------
| 验证token
|--------------------------------------------------------------------------
*/	
	function chktoken($token,$client_key,$device_id)
	{
		$chk = $this->db->query('select `user_id` from `'.$this->db->dbprefix('api_device_sync').'` where `client_key`=\''.$client_key.'\' and `device_id`=\''.$device_id.'\' and `token`=\''.$token.'\' ')->row_array();	
		return $chk;
		//return true;
	}
	
	
/*
|--------------------------------------------------------------------------
|  上传头像
{host}/index.php/api/client/upload_headpic
|--------------------------------------------------------------------------
*/
	function upload_headpic($member_id)
	{
		$query = $this->db->query('select `floder_pre`,`floder` 
			from `'.$this->db->dbprefix('u_account').'` 
			where `id` = \''.intval($member_id).'\'')->row_array();
		if(!isset($query['floder_pre'])){
			return -1;
		}
		

		if($_FILES['userfile']['size']>0){
			$this->load->library('upload');
			$config['upload_path'] = './pic/'.$query['floder_pre'].'/'.$query['floder'].'/company';
			$config['allowed_types'] = '*';
			$config['max_size'] = '50000';
			$config['max_width']  = '6400';
			$config['max_height']  = '6400';
			$config['encrypt_name']  = TRUE;
		
						if(!is_dir($config['upload_path'])){
					mkdir($config['upload_path'],0755,true)	;
				}
		
			$this->load->library('upload', $config);
			$this->upload->initialize($config);
			if (!$this->upload->do_upload())
			{
				$error = array('error' => $this->upload->display_errors());
				//print_r($error);
				return '-60001';
			} else{
				$data = array('upload_data' => $this->upload->data());
				$pic_name = $data['upload_data']['file_name'];
				//print_r($this->upload->data());
			}
			
			$this->db->query('update `'.$this->db->dbprefix('u_banseinfo').'` set
				`member_head`=\''.$pic_name.'\' 
				where   `account_id`=\''.$member_id.'\' ');
			return '1';
		}else{
			return '-60002';	
		}
	
	}	




/*
|--------------------------------------------------------------------------
|  收藏某个企业的所有产品
{host}/index.php/api/client/collect_company_products
|--------------------------------------------------------------------------
*/
	function collect_company_products($member_id,$company_id)
	{
		$pros = $this->db->query('select `id` from  `'.$this->db->dbprefix('u_pro').'` where  `account_id`=\''.$company_id.'\' ')->result_array();
		if(!empty($pros)){
			foreach($pros as $line){
				$sql.=' (\''.$member_id.'\',\''.$line['id'].'\'),';	
			}

			$this->db->query('replace into `'.$this->db->dbprefix('u_product_collect').'` (member_id,product_id) values
			 '.substr($sql,0,-1));	
		}
		return '1';
	}

	
/*
|--------------------------------------------------------------------------
|  根据用户ID获取消息界面基本信息（头像、名称、产品数、最新产品）
{host}/index.php/api/client/collect_company_products
|--------------------------------------------------------------------------
*/	
	function get_mess_memberinfo($member_id,$needinfo='')
	{
		//会员信息
		$res['memberinfo'] = $this->db->query('select a.id,a.floder,a.floder_pre,b.u_name,b.member_head from 
		 `'.$this->db->dbprefix('u_account').'`   a left join `'.$this->db->dbprefix('u_banseinfo').'`  b on a.id=b.account_id where a.id=\''.$member_id.'\' limit 1
		')->row_array();	
		if(!empty($res['memberinfo']['member_head'])){
			$res['memberinfo']['member_head'] = base_url().'pic/'.$res['memberinfo']['floder_pre'].'/'.$res['memberinfo']['floder'].'/company/'.$res['memberinfo']['member_head'];	
		}
		
		if(!$needinfo){
			//最新产品图片
			$proinfo = $this->db->query('select img,type  from 
			 `'.$this->db->dbprefix('u_pro_img').'`    where  `account_id`=\''.$member_id.'\' order by id desc limit 4
			')->result_array();
			//print_r($proinfo);die();
			if(!empty($proinfo)){
				  foreach($proinfo as $picline){
					  if($picline['type']=='0'){
						  $res['pic_array'][] = base_url().'pic/'.$res['memberinfo']['floder_pre'].'/'.$res['memberinfo']['floder'].'/pro/s/'.$picline['img'];		
					  }else{
						  $res['pic_array'][] = $picline['img'];
					  }		
				  }
			}else{
				$res['pic_array'] = array();	
			}
			//产品总数
			$pronum = $this->db->query('select count(*) as pronum  from 
			 `'.$this->db->dbprefix('u_pro').'`    where  `account_id`=\''.$member_id.'\'  
			')->row_array();
			$res['pronum'] = $pronum['pronum'];
		}else{
			$res['pic_array'] = array();
			$res['pronum'] = 0;	
		}
		return $res;
	}
	
	
	
	
/*
|--------------------------------------------------------------------------
|  检查是否已经发起过好友请求
{host}/index.php/api/client/chk_friend_request
|--------------------------------------------------------------------------
*/	
	function chk_friend_request($member_id,$from_member_id,$type='1')
	{
		return  $this->db->query('select id from 
		 `'.$this->db->dbprefix('u_message').'`   where  member_id=\''.$member_id.'\' and  from_member_id=\''.$from_member_id.'\' and type=1 and message_type=\''.$type.'\' limit 1
		')->row_array();	
		
	}	
	
	
	
/*
|--------------------------------------------------------------------------
|  消息轮询
{host}/index.php/api/client/get_message
|--------------------------------------------------------------------------
*/	
	function get_message($member_id,$last_query,$count_per_page)	
	{
		return $this->db->query('select `id` as message_id , member_id as to_member_id  ,  `from_member_id`,`type`,`message`,`message_type`,`title`,`mtime` from  `'.$this->db->dbprefix('u_message').'` where 1 and `type`!=\'3\' and `isread`=\'0\' and  (`member_id`=\''.$member_id.'\' or `member_id`=\'0\') and `mtime`>\''.$last_query.'\' order by `id` desc limit 0,'.$count_per_page.'  ')->result_array();	
	}
	
	function get_im_message($member_id,$last_query,$count_per_page)	
	{
		return $this->db->query('select `id` as message_id , member_id as to_member_id  ,  `from_member_id`,`type`,`message`,`message_type`,`title`,`mtime` from  `'.$this->db->dbprefix('u_message').'` where 1  and `type`=\'3\'  and `isread`=\'0\' and  (`member_id`=\''.$member_id.'\' or `from_member_id`=\''.$member_id.'\') and `mtime`>\''.$last_query.'\' order by `id` asc limit 0,'.$count_per_page.'  ')->result_array();	
	}



/*
|--------------------------------------------------------------------------
|  标识消息已读
{host}/index.php/api/client/set_message_read
|--------------------------------------------------------------------------
*/
	function set_message_read($member_id,$message_ids_array)
	{
		$message_ids = implode(',',$message_ids_array);
		if(!empty($message_ids)){
			$this->db->query('update   `'.$this->db->dbprefix('u_message').'` set `isread`=\'1\' where  id in ('.$message_ids.') and `member_id`=\''.$member_id.'\'  ');
		}
		return '1';
	}	
	


/*
|--------------------------------------------------------------------------
|  导入画册产品
{host}/index.php/api/client/import_pro_from_no4e
|--------------------------------------------------------------------------
*/
	function import_pro_from_no4e($account_id,$no4e_account)
	{
		$this->load->library('Snoopy');	
		$snoopy = new Snoopy();	
		$formvars["company_user"] = $no4e_account;

		//$url = 'http://localhost/suixing';
		$url = 'http://c.no4e.com';
		$action = $url.'/index.php/api/io/import_pro_from_no4e';//表单提交地址
		
		$snoopy->submit($action,$formvars);//$formvars为提交的数组
		$result = $snoopy->results;  //获取表单提交后的 返回的结果
		if(!empty($result)){
			$temp = json_decode($result);
			//print_r($temp);die();
			if(!empty($temp[0]->info->id)){
				foreach($temp as $line){
				//产品基本信息
				$this->db->query('insert into `'.$this->db->dbprefix('u_pro').'` set
				`account_id`=\''.$account_id.'\',
				`proname`=\''.$line->info->proname.'\',
				`create_time`=\''.time().'\',
				`prodes`=\''.$line->info->prodes.'\' ');
				$pid = $this->db->insert_id();
				
				//图片
				if(!empty($line->pic)){
					foreach($line->pic as $picline)	{
						$this->db->query('insert into `'.$this->db->dbprefix('u_pro_img').'` set
						`account_id`=\''.$account_id.'\',
						`pid`=\''.$pid.'\',
						`img`=\'http://c.no4e.com/pic/'.$no4e_account.'/pro/b/'.$picline->img.'\',
						`type`=\'1\' ');	
					}
				}
				
				//标签
				if(!empty($line->tag)){
					foreach($line->tag as $tagline){
						if(!empty($tagline)){
							$sql.=' (\''.$account_id.'\',\''.$pid.'\',\''.trim($tagline->pro_tag).'\'),';	
						}
					}
					$this->db->query('insert into `'.$this->db->dbprefix('u_pro_tag').'` (account_id,pro_id,pro_tag) values
					 '.substr($sql,0,-1));
				}
			}
			}
		}
		return '1';

	}
	
	
}